package com.hao.gulimall.ware.service.impl;

import com.hao.common.constant.WareConstant;
import com.hao.gulimall.ware.entity.PurchaseDetailEntity;
import com.hao.gulimall.ware.service.PurchaseDetailService;
import com.hao.gulimall.ware.vo.MergeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hao.common.utils.PageUtils;
import com.hao.common.utils.Query;

import com.hao.gulimall.ware.dao.PurchaseDao;
import com.hao.gulimall.ware.entity.PurchaseEntity;
import com.hao.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService detailService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {

        //新建，或者已分配状态的采购单
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                .eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode()).or()
                        .eq("status",WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        PurchaseEntity purchase = null;
        if (purchaseId == null){
            //新建采购单
            purchase = new PurchaseEntity();
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(new Date());
            this.save(purchase);
            //合并采购需求
            purchaseId = purchase.getId();
        }else{
            purchase = this.getById(purchaseId);
            //确认采购单状态是0,1才可以合并
            Integer status = purchase.getStatus();
            if (status != WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    && status != WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return;
            }
        }

        //更新时间
        purchase.setUpdateTime(new Date());
        this.updateById(purchase);

        //合并可合并的采购需求到采购单
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntities = items.stream().map(i -> {
            return detailService.getById(i);
        }).filter(entity -> {
            Integer status = entity.getStatus();
            if (status == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()
                   || status == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item ->{
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item.getId());
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        if (detailEntities.size() != 0){
            detailService.updateBatchById(detailEntities);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void received(List<Long> ids) {
        if (ids == null || ids.size() == 0){
            return;
        }
        //1. 确认当前采购单,是新建或者已分配状态,并修改为已领取状态
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(item -> {
            Integer status = item.getStatus();
            if (status == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || status == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item ->{
           item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
           item.setUpdateTime(new Date());
           return item;
        }).collect(Collectors.toList());
        if(purchaseEntities.size() == 0){
            return;
        }
        //2. 改变采购单状态
        this.updateBatchById(purchaseEntities);
        //3. 改变每个采购需求状态
        purchaseEntities.forEach(item ->{
            List<PurchaseDetailEntity> detailEntities = detailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> entities = detailEntities.stream().map(entity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(entity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(entities);
        });
    }

}